package test.src.网络编程;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class MyTcp {
    private BufferedReader reader;
    private ServerSocket serverSocket;
    private Socket socket;
    void getServer() {
        try {
            serverSocket = new ServerSocket(8998);
            System.out.println("服务器套接字已经创建成功了！");
            while (true) {
                System.out.println("等待客户机的连接");
                socket = serverSocket.accept();
                reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                getClientMessage();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void getClientMessage() {
        try {
            while (true) {
                //获取客户端信息
                System.out.println("客户机：" + reader.readLine());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (reader != null) reader.close();
            if (socket != null) socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        MyTcp myTcp = new MyTcp();
        myTcp.getServer();
    }
}
